package telnetserver;

import java.io.*;

public class FileSender extends Thread {
    private User user;
    private FileReader file;
    private Object ret;
    private String[] all;
    private boolean run;
    private boolean pause;
    private int pos;
    private Telnet telnet;
    
    public void addUser(User u) {
        
    }
    
    public FileSender(Telnet t, User u, String fName, Object r) {
        try {
            u.setButtons(null, null);
            telnet = t;
            user = u;
            file = new FileReader(fName);
            ret = r;
            pos = 0;
            run = true;
            pause = false;
            char[] allArray = new char[(int)new File(fName).length()];
            file.read(allArray);
            file.close();
            String s = new String(allArray);
            int tot = 0;
            for (char c : allArray) {
                if (c == 13) tot++;
            }
            all = new String[tot];
            for (int i = 0; i < tot; i++) {
                all[i] = s.substring(0, s.indexOf(13));
                s = s.substring(s.indexOf(13) + 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void run() {
        try {
            for (pos = 0; pos < all.length - 20; pos++) {
                drawAll(pos);
                Thread.sleep(500);
                while (pause) yield();
                if (!run) pos = all.length;
            }
        } catch (Exception e) {}
    }
    
    public void drawAll(int i) {
        user.clear();
        for (int j = 0; j < 20; j++) {
            user.prepare(1, 10, 2 + j, all[i + j]);
        }
        user.prepare(7, 4, 22, "BACK");
        user.prepare(0, 8, 22, "");
        user.send();
    }

    public void read(User u, String s) {
        run = false;
        pause = false;
        telnet.changeMode(u, ret);
    }
    
    public void buttonPressed(User u, int i) {
        switch (i) {
            case 1:
                if (pos > 0) {
                    pause = true;
                    pos--;
                    drawAll(pos);
                }
                break;
            case 2:
                if (pos < all.length - 20) {
                    pause = true;
                    pos++;
                    drawAll(pos);
                }
                break;
            case 3:
                pause = false;
                break;
            case 4:
                pause = true;
                break;
        }
    }
    
    public void remUser(User u) {
        run = false;
    }
    
}
